using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;

namespace alwitTest
{
    public partial class MessageBox : Window
    {
        private bool _done;

        public enum MessageBoxButtons
        {
            Ok,
            OkCancel,
            YesNo,
            YesNoCancel
        }

        public enum MessageBoxResult
        {
            Ok,
            Cancel,
            Yes,
            No
        }

        public MessageBox()
        {
            var iv = this.GetObservable(Window.IsVisibleProperty);
            iv.Subscribe(async value =>
            {
                await Task.Delay(1);
                if (value && !_done)
                {
                    _done = true;
                    SetWindowStartupLocationWorkaround();
                }
            });

            AvaloniaXamlLoader.Load(this);
        }

        private void SetWindowStartupLocationWorkaround()
        {
            if (OperatingSystem.IsWindows())
            {
                // Not needed for Windows
                return;
            }

            var scale = PlatformImpl?.DesktopScaling ?? 1.0;
            var powner = Owner?.PlatformImpl;
            if (powner != null)
            {
                scale = powner.DesktopScaling;
            }

            var rect = new PixelRect(PixelPoint.Origin, PixelSize.FromSize(ClientSize, scale));

            if (WindowStartupLocation == WindowStartupLocation.CenterScreen)
            {
                var screen = Screens.ScreenFromPoint(powner?.Position ?? Position);
                if (screen == null)
                {
                    return;
                }

                Position = screen.WorkingArea.CenterRect(rect).Position;
            }
            else
            {
                if (powner == null || WindowStartupLocation != WindowStartupLocation.CenterOwner)
                {
                    return;
                }

                Position = new PixelRect(powner.Position, PixelSize.FromSize(powner.ClientSize, scale)).CenterRect(rect)
                    .Position;
            }
        }

        public static Task<MessageBoxResult> Show(Window parent, string text, string title, MessageBoxButtons buttons)
        {
            var msgbox = new MessageBox()
            {
                Title = title
            };
            msgbox.FindControl<TextBlock>("Text").Text = text;
            var buttonPanel = msgbox.FindControl<StackPanel>("Buttons");

            var res = MessageBoxResult.Ok;

            void AddButton(string caption, MessageBoxResult r, bool def = false)
            {
                var btn = new Button { Content = caption };
                btn.Click += (_, __) => {
                    res = r;
                    msgbox.Close();
                };
                buttonPanel.Children.Add(btn);
                if (def)
                    res = r;
            }

            if (buttons == MessageBoxButtons.Ok || buttons == MessageBoxButtons.OkCancel)
                AddButton("Ok", MessageBoxResult.Ok, true);
            if (buttons == MessageBoxButtons.YesNo || buttons == MessageBoxButtons.YesNoCancel)
            {
                AddButton("Yes", MessageBoxResult.Yes);
                AddButton("No", MessageBoxResult.No, true);
            }

            if (buttons == MessageBoxButtons.OkCancel || buttons == MessageBoxButtons.YesNoCancel)
                AddButton("Cancel", MessageBoxResult.Cancel, true);


            var tcs = new TaskCompletionSource<MessageBoxResult>();
            msgbox.Closed += delegate { tcs.TrySetResult(res); };
            if (parent != null)
                msgbox.ShowDialog(parent);
            else msgbox.Show();
            return tcs.Task;
        }

    }
}
